﻿
CREATE FUNCTION [dbo].[f_invoice_in_get_rest]
	(
	@p_invoice_in_id int
	)
RETURNS money
AS
	BEGIN
		DECLARE @m_rest_summ money
		DECLARE @m_payments_sum money
		DECLARE @m_invoice_in_sum money
		
		SELECT @m_invoice_in_sum = [dbo].[f_Convert_to_RUR]([SUM], CAST(GETDATE() as DATE), [NSI_CURRENCY_ID])
		FROM [dbo].[INVOICE_IN] 
		WHERE ID = @p_invoice_in_id
	
		SELECT @m_payments_sum = SUM([dbo].[f_Convert_to_RUR](poi.[SUM_CUR], CAST(GETDATE() as DATE), ino.NSI_CURRENCY_ID))		
		FROM PAY_OUT_ON_INV_IN as poi	
		INNER JOIN INVOICE_IN as ino
			ON poi.INVOICE_IN_ID = ino.ID
		WHERE poi.INVOICE_IN_ID = @p_invoice_in_id	
	
		IF @m_payments_sum IS NULL 
		BEGIN
			SET @m_payments_sum = 0
		END
	
		SET @m_rest_summ = @m_invoice_in_sum - @m_payments_sum
		
		RETURN @m_rest_summ
	END